package com.atguigu.gulimall.product.web;

import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {

    @Autowired
    CategoryService categoryService;

    @Autowired
    RedissonClient redissonClient;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping({"/", "/index.html"})
    public String indexPage(Model model) {


        // TODO 1. 查出所有的一级分类
        List<CategoryEntity> categoryEntityList =  categoryService.getLevel1Categorys();

        /**
         * 视图解析器进行拼串
         * 前缀: classpath"/templates/
         * 后缀: .html
         */
        // classpath"/templates/,  .html
        model.addAttribute("categorys", categoryEntityList);
        return "index";
    }

    // index/catalog.json
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> catalogJson = categoryService.getCatalogJson();
        return catalogJson;
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        // 1. 获取一把锁, 只要名字一样,就是同一把锁
        RLock lock = redissonClient.getLock("my-lock");

        // 加锁, 阻塞
        // 1. redisson, 默认的方法有自动续期
//        lock.lock();
        lock.lock(10, TimeUnit.SECONDS);  // 不会自动续期
        // 加锁成功, 执行业务
        try {
            System.out.println("加锁成功, 执行业务");
            try {
                Thread.sleep(30000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {

        }finally {
            // 3. 假设没有运行会不会出现死锁
            System.out.println("释放锁..." + Thread.currentThread().getId());
            lock.unlock();
        }

        return "hello";
    }

    @GetMapping("/write")
    @ResponseBody
    public String writeValue() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        String s = UUID.randomUUID().toString();
        RLock wLock = readWriteLock.writeLock();
        wLock.lock();
        try {
            Thread.sleep(30000);
            stringRedisTemplate.opsForValue().set("writeValue", s);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            wLock.unlock();
        }

        return s;
    }

    @GetMapping("/read")
    @ResponseBody
    public String readValue() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock rLock = readWriteLock.readLock();
        rLock.lock();
        String s = "";
        try {
            s = stringRedisTemplate.opsForValue().get("writeValue");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            rLock.unlock();
        }

        return s;
    }

    /**
     * 车库停车
     * 3车位
     * 信号量也可用于分布式限流
     * @return
     * @throws InterruptedException
     */
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
//        semaphore.acquire();
        boolean b = semaphore.tryAcquire();
        if(b){
            //执行业务
        }else{
            return "请稍后再试";
        }
        return "park" + b;
    }

    @GetMapping("/unpark")
    @ResponseBody
    public String unpark() {
        RSemaphore semaphore = redissonClient.getSemaphore("semaphore");
        semaphore.release();  // 释放一个车位
        return "unpark";
    }

    /**
     * countDownLacth
     * 放假锁门，三个班级全部走完校门锁门
     * 其他的全部执行完才会执行业务
     */
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch latch = redissonClient.getCountDownLatch("anyCountDownLatch");
        latch.trySetCount(3);
        latch.await();
        return "lockDoor";
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() {
        RCountDownLatch latch = redissonClient.getCountDownLatch("anyCountDownLatch");
        latch.countDown();
        return "go";
    }


}
